|
|
|
|
|
|
|
Adding Controls at Runtime |
|
|
|
|
|
|
|
|
After you create the first element of the array, you can use code to add other elements in response to events. For many applications, you add the controls during form load. One application of this technique would be to create a generic data entry form. By using control arrays, you could pass a recordset to the form and then create the number of controls you need to handle however many fields are in the recordset. (Recordsets represent data in a database and are discussed in Chapter 24, ''Database Basics.") |
|
|
|
|
|
|
|
|
To add a control at runtime, you use the Load statement. It is the same statement that you can use to bring a form into memory. With the Load statement, you must specify the name of the control to be loaded and its index. To avoid an error, you must ensure that the index is unique. Note that the new control's Visible property is set to False. The complete process for adding a new control is detailed in the following steps: |
|
|
|
|
|
|
|
|
1. Use the Load statement to create the new control and bring it into memory. |
|
|
|
|
|
|
|
|
2. The new control is shown in the same position as the original control because it inherits the properties of the original control. Therefore, you need to move the new control using the Move method or by setting its Top and Left properties. |
|
|
|
|
|
|
|
|
3. Set the new control's Visible property to True to display it on the form. |
|
|
|
|
|
|
|
|
4. Set any other necessary properties of the new control. (All other properties are inherited from the original designtime control.) |
|
|
|
|
| |
|
|
|
|
Setting the index of the new element to one greater than the UBound property of the array ensures that you will have a unique index. |
|
|
|
|
|
|
|
|
|
|
Now examine this technique by adding it to the sample program. Add a test command button that will be responsible for adding a new element to the txtArray control array. To do so, follow these steps: |
|
|
|
|
|
|
|
|
1. At designtime, set the main form's Height property to 6000. This setting allows plenty of room for the new controls that will be added when the program is running. |
|
|
|
|
|
|
|
|
2. Add a command button in an empty area of the form. Set its Name property to cmdAdd and its Caption property to Add a text box. |
|
|
|
|
|
|
|
|
3. Enter the following code into cmdAdd's Click event procedure: |
|
|
|
|
|
|
|
|
Dim i As Integer
i = txtArray.UBound
Load txtArray(i + 1)
txtArray(i + 1).Visible = True
txtArray(i + 1).Top = txtArray(i).Top + txtArray(i).Height + 120
txtArray(i + 1).Left = txtArray(i).Left |
|
|
|
|
|
|
|
|
The preceding code sets the position of the new control array element to a position 120 twips below the most recently added control (taking into account the control's height as well). Run the program and click the command button to give it a try. Figure 13.6 shows how the form looks after several clicks. |
|
|
|
|
|